<template>
	<view class="u-wrap">
		<u-toast ref="uToast" />
		<u-no-network></u-no-network>
		<u-navbar safeAreaInsetTop fixed placeholder>
			<view slot="left">
				<u-search :showAction="false" shape="round" v-model="searchKey" placeholder="请输入搜索内容" @search="goSearch"></u-search>
			</view>
			<!-- <u-icon name="scan" color="#fff" size="16" slot="right"></u-icon> -->
		</u-navbar>

		<view class="coreshop-padding-10" v-if="CateStyle==1">
			<view v-for="(item,index) in tabbar" :key="index" @click="goClass(item.id)">
				<u--image width="100%" height="195px" :src="item.imageUrl" :showLoading="false"></u--image>
				<view class="coreshop-text-center coreshop-padding-top-10 coreshop-padding-bottom-10">
					{{item.name}}
				</view>
			</view>
		</view>
		<view class="coreshop-padding-10" v-if="CateStyle==2">
			<u-row gutter="16">
				<u-col span="4" v-for="(item,index) in tabbar" :key="index" @click="goClass(item.id)">
					<u--image width="100%" height="80px" :src="item.imageUrl" :showLoading="false"></u--image>
					<view class="coreshop-text-center coreshop-padding-top-15 coreshop-padding-bottom-15 coreshop-font-sm">
						{{item.name}}
					</view>
				</u-col>
			</u-row>
		</view>
		<view class="u-menu-wrap coreshop-flex-direction-row" v-if="CateStyle==3">
			<scroll-view scroll-y scroll-with-animation class="u-tab-view menu-scroll-view" :scroll-top="scrollTop">
				<view 
					v-for="(item,index) in tabbar" 
					:key="index" class="u-tab-item"
					:class="[current==index ? 'u-tab-item-active' : '']" 
					:data-current="index" 
					@tap.stop="swichMenu(index)"
				>
					<text class="u-line-1">{{item.name}}</text>
				</view>
			</scroll-view>
			<block v-for="(item,index) in tabbar" :key="index">
				<scroll-view scroll-y class="right-box" v-if="current==index">
					<view class="coreshop-padding-10">
						<coreshop-advert codes="TplIndexBanner1"></coreshop-advert>
						<view class="class-item">
							<view class="item-title">
								<text>{{item.name}}</text>
							</view>
							<view class="item-container coreshop-flex-direction-row">
								<view class="thumb-box" v-for="(item1, index1) in item.child" :key="index1" @click="goClass(item1.id)">
									<u--image width="60px" height="60px" :src="item1.imageUrl" :showLoading="false">
									</u--image>
									<view class="item-menu-name">{{item1.name}}</view>
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</block>
		</view>
		<view class="u-menu-wrap coreshop-flex-direction-row" v-if="CateStyle==4">
			<view class="main" :style="'height:' + scorllH+'px;'">
				<view class="content" :style="'height:' + scorllH+'px;'">
					<scroll-view class="menus" scroll-with-animation scroll-y :scroll-top="headerH"
						:style="'height:' + scorllH+'px;'">
						<view class="wrapper">
							<view 
								class="menu" :id="`menu-${item.id}`" 
								:class="{'current': item.id === currentCateId}"
								v-for="(item, index) in menus" 
								:key="index" 
								@tap="handleMenuTap(item.id,index)"
							>
								<text>{{ item.name }}</text>
							</view>
						</view>
					</scroll-view>
					<scroll-view class="goods" scroll-with-animation scroll-y :scroll-top="headerH" :style="'height:' + scorllH+'px;'" @scrolltolower="scrolltolower">
						<u-sticky v-if="menuChilds">
							<view class="coreshop-bg-white coreshop-padding-left-10">
								<u-tabs 
									:list="menuChilds" 
									:current="childCurrent"
									:activeStyle="{color: '#303133',fontWeight: 'bold',transform: 'scale(1.05)',fontSize:'14px'}"
									:inactiveStyle="{color: '#606266',transform: 'scale(1)',fontSize:'14px'}"
									@change="childIdCheck"></u-tabs>
							</view>
						</u-sticky>

						<view class="wrapper">
							<view class="list">
								<view class="category" v-for="(good, key) in goodsList" :key="key" :id="`cate-${good.id}`">
									<view class="items">
										<view class="good">
											<view class="image">
												<u--image :showLoading="true" :src="good.image" width="83px" height="83px" radius="4px" @click="goGoodsDetail(good.id)"></u--image>
											</view>
											<view class="right">
												<text class="u-line-2" @tap="goGoodsDetail(good.id)">{{ good.name }}</text>
												<u--text type="info" size="12px" lines="1" :text="good.brief"></u--text>
												<!--<text class="tips u-line-1" @tap="goGoodsDetail(good.id)">{{ good.brief }}</text>-->
												<view class="price_and_action">
													<text class="price">￥{{ good.price }}</text>
													<view class="btn-group">
														<button type="primary" class="btn property_btn" hover-class="none" size="mini" @tap="showGoodSkuModal(good)"> 选规格 </button>
													</view>
												</view>
											</view>
										</view>
									</view>
								</view>
								<u-loadmore :status="loadStatus" :icon-type="iconType" :load-text="loadText" margin-top="20" margin-bottom="20" />
							</view>
						</view>
					</scroll-view>
				</view>
				<!-- 购物车栏 begin -->
				<view class="cart-box">
					<view class="mark">
						<image src="/static/images/common/cart.png" class="cart-img"></image>
						<view class="tag">{{cartNums}}</view>
					</view>
					<view class="price">￥{{cartMoney}}</view>
					<button type="primary" class="pay-btn" @tap="redirectCart()" :disabled="cartNums<=0">去结算</button>
				</view>
				<!-- 购物车栏 end -->
			</view>

			<vk-data-goods-sku-popup 
				ref="skuPopup" 
				v-model="skuKey" 
				border-radius="20" 
				:amount-type="0"
				:localdata="goodsSkuInfo" 
				:mode="skuMode" 
				@open="onOpenSkuPopup" 
				@close="onCloseSkuPopup" 
				@add-cart="addCart"
				@buy-now="buyNow"
			>
			</vk-data-goods-sku-popup>
		</view>

		<!-- 登录提示 -->
		<coreshop-login-modal></coreshop-login-modal>
	</view>
</template>
<script>
	import { mapState } from 'vuex';
	export default {
		data() {
			return {
				tabbar: [],
				scrollTop: 0, //tab标题的滚动条位置
				current: 0, // 预设当前项的值
				menuHeight: 0, // 左边菜单的高度
				menuItemHeight: 0, // 左边菜单item的高度,
				beans: [],
				isChild: false,
				searchKey: '',
				headerH: 0,
				scorllH: 0, //滚动区域全屏
				cartNums: 0, // 购物车数量
				cartMoney: 0, // 购物车数量
				menus: [], //所有分类
				menuChilds: [], //当前分类下子集
				needCurrentCateId: 0, //仿点餐模式下应该获取大类还是小类数据
				childCurrent: 0, //子集默认选中下标
				goodsList: [], //所有商品
				menuScrollIntoView: '',
				good: {},
				currentCateId: 0, //默认分类
				scrollTop: 0,
				loadStatus: 'loadmore',
				loadIconType: 'flower',
				loadText: {
					loadmore: '轻轻上拉',
					loading: '努力加载中',
					nomore: '实在没有了'
				},
				type: 2, // 1加入购物车 2购买
				cartType: this.$globalConstVars.paymentType.common,
				page: 1,
				limit: 10,
				// 是否打开SKU弹窗
				skuKey: false,
				// SKU弹窗模式
				skuMode: 1,
				// 后端返回的商品信息
				goodsSkuInfo: {},
			}
		},
		computed: {
			...mapState({
				hasLogin: state => state.hasLogin,
				userInfo: state => state.userInfo,
			}),
			hasLogin: {
				get() {
					return this.$store.state.hasLogin;
				},
				set(val) {
					this.$store.commit('hasLogin', val);
				}
			},
			userInfo: {
				get() {
					return this.$store.state.userInfo;
				},
				set(val) {
					this.$store.commit('userInfo', val);
				}
			},
			CateStyle() {
				return this.$store.state.config.cateStyle ? this.$store.state.config.cateStyle : 3;
			}
		},
		onLoad() {
			uni.getSystemInfo({
				success: (e) => {
					// #ifndef MP
					this.StatusBar = e.statusBarHeight;
					if (e.platform == 'android') {
						this.headerH = e.statusBarHeight + 50;
					} else {
						this.headerH = e.statusBarHeight + 45;
					};
					// #endif
					this.scorllH = e.windowHeight - e.statusBarHeight - 50;
				}
			})
			// 获取购物车数量
			if (this.$store.state.config.cateStyle == 4) {
				this.goodsList = [];
				this.page = 1;
				this.limit = 10;
				this.categories();
				//this.getCartNums();
			} else {
				this.categories();
			}
		},
		onShow() {
			// 获取购物车数量
			if (this.$store.state.config.cateStyle == 4) {
				this.getCartNums();
			}
		},
		methods: {
			// 点击左边的栏目切换
			async swichMenu(index) {
				if (index == this.current) return;
				this.current = index;
				// 如果为0，意味着尚未初始化
				if (this.menuHeight == 0 || this.menuItemHeight == 0) {
					await this.getElRect('menu-scroll-view', 'menuHeight');
					await this.getElRect('u-tab-item', 'menuItemHeight');
				}
				// 将菜单菜单活动item垂直居中
				this.scrollTop = index * this.menuItemHeight + this.menuItemHeight / 2 - this.menuHeight / 2;
			},
			// 获取一个目标元素的高度
			getElRect(elClass, dataVal) {
				console.log('ds', elClass, dataVal)
				new Promise((resolve, reject) => {
					const query = uni.createSelectorQuery().in(this);
					query.select('.' + elClass).fields({
						size: true
					}, res => {
						// 如果节点尚未生成，res值为null，循环调用执行
						if (!res) {
							setTimeout(() => {
								this.getElRect(elClass);
							}, 10);
							return;
						}
						this[dataVal] = res.height;
					}).exec();
				})
			},
			goClass(catId) {
				uni.navigateTo({
					url: '/pages/category/list/list?id=' + catId
				});
			},
			goSearch() {
				if (this.searchKey != '') {
					this.$u.route('/pages/category/list/list?key=' + this.searchKey);
				} else {
					this.$refs.uToast.show({
						message: '请输入查询关键字',
						type: 'warning',
					})
				}
			},
			categories() {
				this.$u.api.categories().then(res => {
					if (res.status) {
						this.tabbar = res.data;
						if (this.$store.state.config.cateStyle == 4) {
							this.menus = res.data;
							if (res.data.length > 0) {
								for (var i = 0; i < res.data.length; i++) {
									if (res.data[i].child) {
										let item = {
											id: 0,
											imageUrl: "",
											name: "全部",
											sort: 0,
										}
										res.data[i].child.unshift(...[item])
									}
								}
								this.currentCateId = res.data[0].id;
								this.needCurrentCateId = res.data[0].id;
								this.menuChilds = res.data[0].child;
								this.getGoods();
							}
						}
					}
				});
			},
			// 打开sku弹出
			openSkuPopup() {
				this.skuKey = true;
			},
			closeSkuPopup() {
				this.skuKey = false;
			},
			// sku组件监听
			onOpenSkuPopup() {
				//console.log("监听 - 打开sku组件");
			},
			onCloseSkuPopup() {
				//console.log("监听 - 关闭sku组件");
			},
			showGoodSkuModal(item) {
				if (item.id) {
					this.getGoodsDetail(item.id);
				}
			},
			// 获取商品详情
			getGoodsDetail(goodsId) {
				uni.showLoading({
					title: '加载中'
				});
				let _this = this;
				let data = {
					id: goodsId,
					data: true
				}
				// 如果用户已经登录 要传用户token
				let userToken = this.$db.get("userToken");
				if (userToken) {
					this.$u.api.goodsDetailByToken(data).then(res => {
						if (res.status == true) {
							_this.goodsSkuInfo = res.data.skuList;
							_this.openSkuPopup();
							setTimeout(function() {
								uni.hideLoading();
							}, 1000);
						} else {
							_this.$refs.uToast.show({
								message: res.msg,
								type: 'error',
								complete: function() {
									uni.navigateBack({
										delta: 1
									});
								}
							})
							uni.hideLoading();
						}
					})
				} else {
					this.$u.api.goodsDetail(data).then(res => {
						if (res.status == true) {
							_this.goodsSkuInfo = res.data.skuList;
							_this.openSkuPopup();
							setTimeout(function() {
								uni.hideLoading();
							}, 1000);
						} else {
							_this.$refs.uToast.show({
								message: res.msg,
								type: 'error',
								complete: function() {
									uni.navigateBack({
										delta: 1
									});
								}
							})
							uni.hideLoading();
						}
					})
				}
			},
			// 加入购物车按钮
			addCart(selectShop) {
				var that = this;
				uni.showLoading({
					title: '加载中'
				});
				if (!this.hasLogin) {
					uni.hideLoading();
					this.$store.commit('showLoginTip', true);
					return false;
				}
				if (selectShop.buy_num > 0) {
					let data = {
						productId: selectShop._id,
						nums: selectShop.buy_num,
						type: 1,
					}
					this.$u.api.addCart(data).then(res => {
						if (res.status) {
							uni.hideLoading();
							that.getCartNums(); // 获取购物车数量
							that.$refs.uToast.show({
								message: res.msg,
								type: 'success'
							});
						} else {
							that.$u.toast(res.msg);
							uni.hideLoading();
						}
					});
				}
				that.closeSkuPopup();
			},
			// 立即购买
			buyNow(selectShop) {
				var that = this;
				uni.showLoading({
					title: '加载中'
				});
				if (!this.hasLogin) {
					uni.hideLoading();
					this.$store.commit('showLoginTip', true);
					return false;
				}
				if (selectShop.buy_num > 0) {
					let data = {
						productId: selectShop._id,
						nums: selectShop.buy_num,
						type: 2,
						cartType: this.cartType
					}
					this.$u.api.addCart(data).then(res => {
						if (res.status) {
							let cartIds = res.data;
							that.$u.route('/pages/placeOrder/index/index?cartIds=' + JSON.stringify(cartIds));
							uni.hideLoading();
						} else {
							this.$u.toast(res.msg);
							uni.hideLoading();
						}
					});
				}
				that.closeSkuPopup();
			},

			handleMenuTap(id, index) {

				var _this = this;
				this.currentCateId = id;
				this.needCurrentCateId = id;

				this.childCurrent = 1;
				console.log('childCurrent', this.childCurrent);

				this.menuChilds = [];
				this.menuChilds = _this.menus[index].child;

				this.childCurrent = 0;
				console.log('childCurrent', this.childCurrent);
				this.$forceUpdate()

				this.page = 1;
				this.goodsList = [];
				this.getGoods(0);

			},
			childIdCheck(e) {
				if (e.id != 0) {
					this.needCurrentCateId = e.id;
				} else {
					this.needCurrentCateId = this.currentCateId;
				}
				this.page = 1;
				this.goodsList = [];
				this.getGoods();
			},
			scrolltolower() {
				console.log("触底了");
				if (this.loadStatus != 'nomore') {
					this.getGoods();
				}
			},
			//取得商品数据
			getGoods: function() {
				uni.showLoading({
					title: '加载中'
				});
				var _this = this;
				let data = {
					page: this.page,
					limit: this.limit,
				};
				var where = {
					catId: this.needCurrentCateId,
				};
				data.where = JSON.stringify(where);
				_this.$u.api.goodsList(data).then(res => {
					if (res.status) {
						const _list = res.data.list;
						_this.goodsList = [..._this.goodsList, ..._list];
						if (res.data.totalPages >= _this.page) {
							_this.loadStatus = 'loadmore';
							_this.page++;
						} else {
							// 数据已加载完毕
							_this.loadStatus = 'nomore';
						}
						uni.hideLoading();
					} else {
						// 接口请求出错了
						uni.hideLoading();
						this.$u.toast(res.msg);
					}
				});
			},
			// 获取购物车数量
			getCartNums() {
				let userToken = this.$db.get("userToken");
				if (userToken && userToken != '') {
					// 获取购物车数量
					this.$u.api.getCartNumAndMoney().then(res => {
						if (res.status) {
							this.cartNums = res.data.count;
							this.cartMoney = res.data.money;
							console.log(this.cartNums);
						}
					})
				}
			},
		}
	}
</script>
<style lang="scss" scoped>
	@import "index.scss";
</style>